#include "MemJson.h"

namespace x2lib
{
#pragma region MemJsonBase

    MemJsonBase::MemJsonBase()
    {
        init();
    }

    MemJsonBase::~MemJsonBase()
    {
        if (IsRoot() && 0 != __cap__)
        { // 仅对对象型根节点进行释放（引用型节点__cap__==0）
            free(__mem__);
        }
        if (__buff__ != nullptr)
        {
            free(__buff__);
        }
    }

    MemJsonBase::MemJsonBase(THIS_XTYV this_xtyv)
    {
        memset(this, 0, sizeof(MemJsonBase)); // 引用的__cap__必须设为0
        __temp__ = true;
        __parent__ = (MemJsonBase*)this_xtyv.pThis;
        __mem__ = this_xtyv.uXtyV;
        MemJsonBase::Check(__mem__, &__cnt__);
    }

    bool MemJsonBase::IsRoot() const { return (nullptr == __parent__); }

    void* MemJsonBase::Mem() const { return __mem__; }

    uint32_t MemJsonBase::Len() const
    {
        uint32_t* p_len = (uint32_t*)Mem();
        return *p_len;
    };

    uint32_t MemJsonBase::Cnt() const { return __cnt__; }

    void MemJsonBase::Reset() 
    {
        if (IsRoot() && 0 != __cap__)
        { // 仅对对象型根节点进行释放（引用型节点__cap__==0）
            free(__mem__);
        }
        if (__buff__ != nullptr)
        {
            free(__buff__);
        }

        init();
    }

    MemJsonBase& MemJsonBase::Put(const char* szKey, const bool bVal)
    {
        __Put(szKey, 'B', &bVal, sizeof(bVal));
        return *this;
    }

    MemJsonBase& MemJsonBase::Put(const char* szKey, const int32_t iVal)
    {
        __Put(szKey, 'I', &iVal, sizeof(iVal));
        return *this;
    }

    MemJsonBase& MemJsonBase::Put(const char* szKey, const int64_t iVal)
    {
        __Put(szKey, 'U', &iVal, sizeof(iVal));
        return *this;
    }

#if 0
    MemJsonBase& MemJsonBase::Put(const char* szKey, const void* vPtr)
    {
        __Put(szKey, 'P', &vPtr, sizeof(vPtr));
        return *this;
    }
#endif

    MemJsonBase& MemJsonBase::Put(const char* szKey, const double dVal)
    {
        __Put(szKey, 'F', &dVal, sizeof(dVal));
        return *this;
    }

    MemJsonBase& MemJsonBase::Put(const char* szKey, const char* sVal)
    {
        if (sVal == nullptr)
        {
            Put(szKey);
        }
        else
        {
            __Put(szKey, 'S', sVal, strlen(sVal) + 1);
        }
        return *this;
    }

    MemJsonBase& MemJsonBase::Put(const char* szKey)
    {
        __Put(szKey, 'N', nullptr, 0);
        return *this;
    }

    MemJsonBase& MemJsonBase::Puts(const char* szKey, const char* szFmt, ...)
    {
        if (szFmt == nullptr)
        {
            Put(szKey);
        }
        else
        {
            va_list body;
            va_start(body, szFmt);
            _Put(szKey, szFmt, body);
            va_end(body);
        }
        return *this;
    }

    MemJsonBase& MemJsonBase::Put(const char* szKey, void* pBin, uint32_t nBin)
    {
        __Put(szKey, 'H', pBin, nBin);
        return *this;
    }

    MemJsonBase& MemJsonBase::Put(const char* szKey, MemJsonBase& dx)
    {
        __Put(szKey, 'M', (void*)dx.Mem(), dx.Len());
        return *this;
    }

    MemJsonBase& MemJsonBase::Add(const bool bVal)
    {
        return Put("", bVal);
    }

    MemJsonBase& MemJsonBase::Add(const int32_t iVal)
    {
        return Put("", iVal);
    }

    MemJsonBase& MemJsonBase::Add(const int64_t iVal)
    {
        return Put("", iVal);
    }

    MemJsonBase& MemJsonBase::Add(const double dVal)
    {
        return Put("", dVal);
    }

    MemJsonBase& MemJsonBase::Add(const char* sVal)
    {
        return Put("", sVal);
    }

    MemJsonBase& MemJsonBase::Add()
    {
        return Put("");
    }

    MemJsonBase& MemJsonBase::Adds(const char* szFmt, ...)
    {
        if (szFmt == nullptr)
        {
            Add();
        }
        else
        {
            va_list body;
            va_start(body, szFmt);
            _Put("", szFmt, body);
            va_end(body);
        }
        return *this;
    }

    MemJsonBase& MemJsonBase::Add(void* pBin, uint32_t nBin)
    {
        return Put("", pBin, nBin);
    }

    MemJsonBase& MemJsonBase::Add(MemJsonBase& dx)
    {
        return Put("", dx);
    }

    MemJsonBase& MemJsonBase::_Put(const char* szKey, const char* szFmt, va_list body)
    {
        char* pData = (char*)malloc(MemJsonBase::COB);
        int nData = vsnprintf(pData, MemJsonBase::COB, (char*)szFmt, body) + 1;
        if (nData > MemJsonBase::COB)
        {
            pData = (char*)realloc(pData, nData);
            vsnprintf(pData, nData, (char*)szFmt, body);
        }
        pData[nData] = 0;
        __Put(szKey, 'S', pData, nData);
        free(pData);

        return *this;
    }

    MemJsonBase::ValBase MemJsonBase::__Put(const char* szKey, char t, const void* pBin, uint32_t nBin)
    {
        const char* pKey = (szKey ? szKey : "\0");
        int klen = strlen(pKey) + 1;
        uint32_t newlen = klen + sizeof(ValBase::T) + sizeof(ValBase::n) + nBin;
        uint64_t p_mem = 0;

        ValBase x = Get(pKey);
        int iKey = x.i;
        if (x.IsValid())
        {
            p_mem = (uint64_t)x._p_;
            move_memory(&p_mem, x._n_, newlen); // p_mem传入的是x.k的起始值，因此后面需要重新修正x.k
        }
        else
        {
            p_mem = (uint64_t)__mem__ + (*(uint32_t*)__mem__); // 追加到尾部
            iKey = __cnt__++; // move_memory内会用到__cnt__
            move_memory(&p_mem, 0, newlen);
        }
        memcpy((void*)p_mem, pKey, klen);
        *(char*)(p_mem + klen) = t;
        *(uint32_t*)(p_mem + klen + sizeof(ValBase::T)) = nBin;
        if (pBin != nullptr || nBin != 0)
        {
            memcpy((void*)(p_mem + klen + sizeof(ValBase::T) + sizeof(ValBase::n)), pBin, nBin);
        }

        x.read((void*)p_mem, x.i);
        return x;
    }

    void MemJsonBase::move_memory(uint64_t* p_mem, uint32_t len, uint32_t xlen)
    {
        int diff = xlen - len;

        MemJsonBase* p_root = this;
        while (p_root->__parent__) // 逐级更新父节点的（根节点在下面处理）：__cap__ __len__
        {
            uint32_t* p_len = (uint32_t*)p_root->__mem__;
            p_root->__cap__ = *p_len + diff;
            *p_len = p_root->__cap__; // 更新当前节点的__len__
            *(uint32_t*)((uint64_t)p_root->__mem__ - sizeof(ValBase::n)) = p_root->__cap__; // 更新当前节点在所属ValBase的n
            p_root = p_root->__parent__;
        }

        //MemJsonBase* p_rroot = nullptr;
        //if (IsQuote())
        //{
        //	p_rroot = p_root;
        //	p_root = p_root->__parent__;
        //}

        uint64_t old_mem = (uint64_t)p_root->__mem__; // 记录realloc前的根节点__mem__

        // 搬运数据，经过上面的迭代，以下代码只针对根节点操作
        if (diff < 0)
        { // 数据收缩，前移mem+len处的数据
            uint32_t* p_len = (uint32_t*)p_root->__mem__;
            memmove((void*)((*p_mem) + xlen), (void*)((*p_mem) + len), *p_len - ((*p_mem) + len - (uint64_t)p_root->__mem__));
            *p_len += diff;
            int _collect_bytes = p_root->__cap__ - *p_len;
            if (_collect_bytes > MemJsonBase::GC_SIZE)
            { // 垃圾回收
                _collect_bytes -= (MemJsonBase::GC_SIZE * (_collect_bytes / MemJsonBase::GC_SIZE));
                p_root->__cap__ -= _collect_bytes;
                p_root->__mem__ = realloc((void*)p_root->__mem__, p_root->__cap__); // 收缩数据一般不会改变内存指针
            }
        }
        else if (diff > 0)
        { // 数据扩充，后移mem处的数据
            uint32_t* p_len = (uint32_t*)p_root->__mem__;
            uint32_t len_old = *p_len;
            *p_len += diff;
            uint64_t ofs = (*p_mem) - (uint64_t)p_root->__mem__; // 计算偏移，因为realloc后__mem__可能会变
            if (*p_len > p_root->__cap__)
            {
                p_root->__cap__ += (diff > MemJsonBase::COB ? diff : MemJsonBase::COB);
                p_root->__mem__ = realloc(p_root->__mem__, p_root->__cap__);
                p_len = (uint32_t*)p_root->__mem__;
            }
            (*p_mem) = (uint64_t)p_root->__mem__ + ofs;  // 更新并回传给调用者

            memmove((void*)((*p_mem) + xlen), (void*)((*p_mem) + len), len_old - ofs - len);
        }

        // 更新所有父节点的（根节点已在上面处理）__mem__
        uint64_t new_mem = (uint64_t)p_root->__mem__; // 记录realloc前的根节点__mem__
        p_root = this;
        while (p_root->__parent__)
        {
            *(uint64_t**)p_root->__mem__ += (new_mem - old_mem);
            p_root = p_root->__parent__;
        }

        //if (p_rroot)
        //{
        //	//p_rroot->__cap__ = 0; // p_root->__cap__;
        //	p_rroot->__mem__ = p_root->__mem__;
        //	p_root->__cnt__ = p_rroot->__cnt__;
        //}
    }

    bool MemJsonBase::Del(const char* szKey)
    {
        ValBase x = this->Get(szKey);
        return Del(x.i);
    }

    bool MemJsonBase::Del(int iKey)
    {
        ValBase x = this->Get(iKey);
        if (x.IsValid())
        {
            --__cnt__;
            move_memory((uint64_t*)&x._p_, x._n_, 0); // 一旦x._p_被move_memory更改，则x失效
            return true;
        }
        return false;
    }

    void MemJsonBase::Clear()
    {
        __cnt__ = 0;
        move_memory((uint64_t*)&__mem__, Len(), MemJsonBase::MIN_LEN);
    }

    bool MemJsonBase::IsArr() const
    {
        return !(__cnt__ > 0 && Get(0).k[0]);
    }

    bool MemJsonBase::IsJSON() const
    {
        return true;
    }

    MemJsonBase::THIS_XTYV MemJsonBase::operator[](const char* szKey)
    {
        THIS_XTYV tx;
        ValBase x = Get(szKey);
        //if (x.IsValid() && x.T == 'M')
        {
            tx.pThis = this;
            tx.uXtyV = x.v;
        }
        return tx;
    }

    MemJsonBase::THIS_XTYV MemJsonBase::operator[](int iKey)
    {
        THIS_XTYV tx;
        ValBase x = Get(iKey);
        //if (x.IsValid() && x.T == 'M')
        {
            tx.pThis = this;
            tx.uXtyV = x.v;
        }
        return tx;
    }

    MemJsonBase::THIS_XTYV MemJsonBase::operator()(const char* szKey)
    {
        ValBase x = Get(szKey);
        if (!x.IsValid() || x.T != 'M')
        {
            uint32_t len = MemJsonBase::MIN_LEN;
            MemJsonBase::ValBase vb = __Put(szKey, 'M', (void*)&len, MemJsonBase::MIN_LEN);
            void* p_mem = vb._p_;
            x.read(p_mem, __cnt__ - 1);
        }
        THIS_XTYV tx;
        tx.pThis = this;
        tx.uXtyV = x.v;
        return tx;
    }

    MemJsonBase::ValBase MemJsonBase::Get(int iKey) const
    {
        if (__mem__ != 0 && iKey >= 0 && iKey < __cnt__)
        {
            ValBase x_temp((void*)((uint64_t)__mem__ + MemJsonBase::MIN_LEN));
            for (uint32_t i = 0;;)
            {
                if (i == iKey) return x_temp;
                if (++i >= __cnt__) break;
                x_temp.read((void*)((uint64_t)x_temp._p_ + x_temp._n_), i);
            }
        }

        return ValBase();
    }

    MemJsonBase::ValBase MemJsonBase::Get(const char* szKey) const
    {
        if (szKey && szKey[0] && __cnt__ != 0)
        {
            ValBase x_temp((void*)((uint64_t)__mem__ + MemJsonBase::MIN_LEN));
            for (uint32_t i = 0;;)
            {
                if (!x_temp.IsValid())
                    break;
                if (strcmp(x_temp.k, szKey) == 0)
                    return x_temp;
                if (++i >= __cnt__)
                    break;
                x_temp.read((void*)((uint64_t)x_temp._p_ + x_temp._n_), i);
            }
        }

        return ValBase();
    }

    int MemJsonBase::LastError()
    {
        return __err__;
    }

    bool MemJsonBase::IsValid()
    {
        return MemJsonBase::Check((void*)__mem__, &__cnt__);
    }

    bool MemJsonBase::IsTemp()
    {
        return __temp__;
    }

    bool MemJsonBase::Build(void* pMem, uint32_t nLen)
    {
        if (!IsRoot() || IsTemp() || !pMem || nLen < *(uint32_t*)pMem)
        {
            return false;
        }

        if (__mem__) { free((void*)__mem__); }
        if (__buff__) { free((void*)__buff__); }

        __cap__ = *(uint32_t*)pMem;
        __mem__ = malloc(__cap__);
        memcpy((void*)__mem__, pMem, __cap__);
        __parent__ = nullptr;
        __err__ = 0;
        __buff__ = nullptr;
        MemJsonBase::Check((void*)__mem__, &__cnt__);
        return true;
    }

    void MemJsonBase::init()
    {
        memset(this, 0, sizeof(MemJsonBase));
        __cap__ = MemJsonBase::MIN_LEN;
        __mem__ = malloc(__cap__);
        *(uint32_t*)__mem__ = MemJsonBase::MIN_LEN;
    }

    bool MemJsonBase::Check(void* pMem, uint32_t* pnCnt)
    {
        if (!pMem) return false;


        uint32_t cnt = 0;
        uint32_t len = *(uint32_t*)pMem;
        if (pMem && MemJsonBase::MIN_LEN == len)
        {
            if (pnCnt != nullptr) *pnCnt = 0;
            return true;
        }

        ValBase x_temp((void*)((uint64_t)pMem + MemJsonBase::MIN_LEN));
        uint32_t sumlen = MemJsonBase::MIN_LEN;
        do
        {
            if (!x_temp.IsValid())
                return false;
            sumlen += x_temp._n_;
            if (sumlen > len) return false;

            ++cnt;
            if (sumlen == len) break;

            x_temp.read((void*)((uint64_t)pMem + sumlen), cnt);
        } while (true);
        if (pnCnt != nullptr) *pnCnt = cnt;
        return true;
    }

#if __SUPPORT_STD_JSON__
#include "depends/cJSON.h"
    bool parse_cJSON(MemJsonBase* pMemJson, cJSON* item)
    {
        for (cJSON* it = item; it != NULL; it = it->next)
        {
            switch (it->type)
            {
            case cJSON_False:
            case cJSON_True:
            {
                pMemJson->Put(it->string, (bool)it->valueintbool);
            }break;
            case cJSON_NULL:
            {
                pMemJson->Put(it->string);
            }break;
            case cJSON_Number:
            {
                if (it->valueintbool)
                {
                    pMemJson->Put(it->string, (int)it->valuedouble);
                }
                else
                {
                    pMemJson->Put(it->string, it->valuedouble);
                }
            }break;
            case cJSON_String:
            {
                pMemJson->Put(it->string, it->valuestring);
            }break;
            case cJSON_Array:
            case cJSON_Object:
            {
                MemJsonBase dx;
                parse_cJSON(&dx, it->child);
                pMemJson->Put(it->string, dx);
            }break;
            case cJSON_Raw:
            case cJSON_Invalid:
            default:break;
            }
        }
        return true;
    }

    void print_cJSON(MemJsonBase* pMemJson, cJSON* item, bool prtBin)
    {
        for (uint32_t i = 0; i < pMemJson->Cnt(); i++)
        {
            MemJsonBase::ValBase x = pMemJson->Get(i);
            char szMemKey[64] = { 0 };
            if (prtBin && (!x.k || x.k[0] == 0))
            {
                sprintf(szMemKey, "mem_0x%08X", x.v);
                x.k = szMemKey;
            }
            switch (x.T)
            {
            case 'N': cJSON_AddNullToObject(item, x.k); break;
            case 'M':
            {
                cJSON* p_item = nullptr;
                //MemJson::Ref mjr = (*pMemJson)[x.i].ToRef();
                MemJson::Ref mjr(pMemJson, pMemJson->Get(x.i).v, pMemJson->Get(x.i).n);
                if (mjr.IsArr()) { p_item = cJSON_AddArrayToObject(item, x.k); }
                else { p_item = cJSON_AddObjectToObject(item, x.k); }
                print_cJSON(&mjr, p_item, prtBin);
            }break;
            case 'V':
            { // 使用索引值访问pMemJson，不要使用键名，因为子元素可能无键名
                //MemJson::Ref mjr = (*pMemJson)[x.i].ToRef();
                MemJson::Ref mjr(pMemJson, pMemJson->Get(x.i).v, pMemJson->Get(x.i).n);
                print_cJSON(&mjr, cJSON_AddArrayToObject(item, x.k), prtBin);
            }break;
            case 'I': cJSON_AddNumberToObject(item, x.k, x.I, 1); break;
            case 'U': cJSON_AddNumberToObject(item, x.k, x.U, 1); break;
            case 'F': cJSON_AddNumberToObject(item, x.k, x.F, 0); break;
            case 'S': cJSON_AddStringToObject(item, x.k, x.S); break;
            case 'B': cJSON_AddBoolToObject(item, x.k, x.I); break;
            case 'H':
            {
                if (prtBin)
                {
                    char szVal[64] = { 0 };
                    sprintf(szVal, "stream_%d", x.n);
                    cJSON_AddStringToObject(item, x.k, szVal);
                }
            }break;
            default:break;
            }
        }
    }

    bool MemJsonBase::Parse(const char* pJson)
    {
        Clear();

        cJSON* root = cJSON_Parse(pJson);
        if (root)
        {
            parse_cJSON(this, root->child);
            cJSON_Delete(root);
            return true;
        }
        return false;
    }

    bool MemJsonBase::Print(char* pJson, int nJson, bool isFmt, bool prtBin)
    {
        cJSON* root = nullptr;
        if (this->IsArr())
        {
            root = cJSON_CreateArray();
        }
        else
        {
            root = cJSON_CreateObject();
        }
        MemJson::Ref mjr(this, this->Mem());
        print_cJSON(&mjr, root, prtBin);

        bool isSucc = cJSON_PrintPreallocated(root, pJson, nJson, isFmt);
        cJSON_Delete(root);
        return isSucc;
    }

    char* MemJsonBase::Print(bool isFmt, int* pnJson, bool prtBin)
    {
        if (pnJson) *pnJson = 0;
        if (__buff__ != nullptr) { free(__buff__); }
        int buffsize = this->Len() * 2;
        __buff__ = (char*)malloc(buffsize);
        if (Print(__buff__, buffsize, isFmt, prtBin))
        {
            if (pnJson) *pnJson = strlen(__buff__);
            return __buff__;
        }

        return nullptr;
    }
#endif

#pragma endregion

#pragma region MemJsonBase::ValBase


    /*******************************************************************MemJsonBase::ValBase****************************************************************/
    MemJsonBase::ValBase::ValBase(void* _k_mem)
    {
        obj = nullptr;
        read(_k_mem, 0);
    };

    // 有键无值
    bool MemJsonBase::ValBase::IsNull() { return  (k != nullptr && v != 0 && n == 0 && T == 'N'); };
    bool MemJsonBase::ValBase::IsValid() { return  (k != nullptr && v != 0); };

#if 0
    MemJsonBase::ValBase::operator int() { return I; }
    MemJsonBase::ValBase::operator bool() { return (bool)I; }
    MemJsonBase::ValBase::operator double() { return F; }
    MemJsonBase::ValBase::operator const char* () { return S; }
    MemJsonBase::ValBase::operator MemJsonBase::ValBase() { return toRef(); };
#endif

    int MemJsonBase::ValBase::stoI() { return atoi(S); }
    double MemJsonBase::ValBase::stoF() { return atof(S); }
    double MemJsonBase::ValBase::stoB() { return (0 != atoi(S)); }

    // iKey只用来设置
    bool MemJsonBase::ValBase::read(void* _k_mem, int iKey)
    {
        memset(this, 0, sizeof(ValBase));
        i = -1;
        if (_k_mem != 0)
        {
            i = iKey;
            k = (char*)_k_mem;
            uint32_t klen = strlen(k) + 1;
            T = *(char*)((uint64_t)_k_mem + klen);
            n = *(uint32_t*)((uint64_t)_k_mem + klen + sizeof(ValBase::T));
            v = (void*)((uint64_t)_k_mem + klen + sizeof(ValBase::T) + sizeof(ValBase::n));
            _n_ = klen + sizeof(ValBase::T) + sizeof(ValBase::n) + n;

            F = *(double*)v;
            B = *(bool*)v;
            I = *(int32_t*)v;
            U = *(int64_t*)v;
            S = (char*)v;

#if 0 // 不要使问题复杂化
            //if (T == 'F') { F = *(double*)v; I = (int32_t)F; B = (bool)F; U = (uint64_t)F; }
            //else if(T == 'B') { F = (float)B; I = (int)B; U = (uint64_t)B; }
            //else if (T == 'U') { F = *(float*)U; I = *(int32_t*)U; B = (bool)U; }
            //else if (T == 'I') { F = (float)I; B = (bool)I; }
            //else if (T == 'S') {}
#endif

            return true;
        }
        return false;
    };

#pragma endregion

#pragma region MemJson::Ref
    MemJson::Ref::Ref()
    {
        __is_valid__ = false;
        __mem__ = 0;
        __cnt__ = 0;
        __parent__ = nullptr;
    }
    MemJson::Ref::Ref(MemJsonBase* parent, void* mem, uint32_t len)
    {
        __parent__ = parent;
        __is_valid__ = hook(mem, len);
    }
    MemJson::Ref::Ref(const MemJson::Ref& mjr)
    {
        __is_valid__ = hook(mjr.Mem(), mjr.Len());
        __parent__ = mjr.__parent__;
    }
    MemJson::Ref::Ref(const MemJson& mj)
    {
        __is_valid__ = hook(mj.Mem(), mj.Len());
        __parent__ = mj.GetParent();
    }
    MemJson::Ref::~Ref()
    {
        __mem__ = 0;
        __cnt__ = 0;
        __is_valid__ = false;
    }
    MemJson::Ref::Ref(THIS_XTYV this_xtyv)
    {
        memset(this, 0, sizeof(MemJsonBase)); // 引用的__cap__必须设为0
        __temp__ = true;
        __parent__ = (MemJsonBase*)this_xtyv.pThis;
        __mem__ = this_xtyv.uXtyV;
        MemJsonBase::Check((void*)__mem__, &__cnt__);
    }
    MemJson::Ref MemJson::Ref::New(const char* pszKey)
    {
        MemJson mj;
        MemJsonBase::ValBase vb = __Put(pszKey, 'M', (void*)mj.Mem(), mj.Len());
        return MemJson::Ref(this, vb.v, vb.n);
    };
    bool MemJson::Ref::Reset(void* mem, uint32_t len)
    {
        __is_valid__ = false;
        __mem__ = 0;
        __cnt__ = 0;
        __parent__ = nullptr;
        if (mem != 0) { __is_valid__ = hook(mem, len); }
        return __is_valid__;
    }
    bool MemJson::Ref::IsValid() { return __is_valid__; }

    // 从MemJson开放出来
    MemJson::Ref MemJson::Ref::operator [](const char* szKey) { return MemJsonBase::operator[](szKey); };
    MemJson::Ref MemJson::Ref::operator [](int iKey) { return MemJsonBase::operator[](iKey); };
    MemJson::Val MemJson::Ref::Get(int iKey) const { return MemJsonBase::Get(iKey); };
    MemJson::Val MemJson::Ref::Get(const char* szKey) const { return MemJsonBase::Get(szKey); };

    bool MemJson::Ref::hook(void* mem, uint32_t len)
    {
        if (len == 0) len = *(uint32_t*)mem;

        __is_valid__ = MemJson::Check(mem, &__cnt__);
        if (!__is_valid__)
            return false;
        __mem__ = mem;
        return true;
    }
#pragma endregion


#pragma region MemJson

    MemJson::MemJson()
    {
        init();
    }

    MemJson::MemJson(const char* szJson)
    {
        init();
        Parse(szJson);
    }

    MemJson::MemJson(void* mem, uint32_t len)
    {
        init();
        if (*(uint32_t*)mem == len)
        {
            __cap__ = *(uint32_t*)mem;
            __mem__ = malloc(__cap__);
            memcpy(__mem__, mem, __cap__);
            __parent__ = nullptr;
            __err__ = 0;
            __buff__ = nullptr;
            MemJson::Check(__mem__, &__cnt__);
        }
    }

    MemJson::MemJson(const MemJson& mj)
    {
        memset(this, 0, sizeof(MemJsonBase));

        __cap__ = *(uint32_t*)mj.__mem__;
        __mem__ = malloc(__cap__);
        memcpy(__mem__, mj.__mem__, __cap__);
        __parent__ = nullptr;
        __err__ = 0;
        __buff__ = nullptr;
        MemJson::Check(__mem__, &__cnt__);
    }
    MemJson& MemJson::operator=(const MemJson& mj)
    {
        memset(this, 0, sizeof(MemJsonBase));

        __cap__ = *(uint32_t*)mj.__mem__;
        __mem__ = malloc(__cap__);
        memcpy(__mem__, mj.__mem__, __cap__);
        __parent__ = nullptr;
        __err__ = 0;
        __buff__ = nullptr;
        MemJson::Check(__mem__, &__cnt__);

        return *this;
    }

    MemJson::MemJson(const int iVal)
    {
        init();
        MemJsonBase::Add(iVal);
    }

    MemJson::MemJson(const bool bVal)
    {
        init();
        MemJsonBase::Add(bVal);
    }

    MemJson::MemJson(const double dVal)
    {
        init();
        MemJsonBase::Add(dVal);
    }

    MemJson::MemJson(const char* szKey, const int iVal)
    {
        init();
        __Put(szKey, 'I', &iVal, sizeof(iVal));
    }

    MemJson::MemJson(const char* szKey, const bool bVal)
    {
        init();
        __Put(szKey, 'B', &bVal, sizeof(bVal));
    }

    MemJson::MemJson(const char* szKey, const double dVal)
    {
        init();
        __Put(szKey, 'F', &dVal, sizeof(dVal));
    }

    MemJson::MemJson(const char* szKey, const char* szFmt, ...)
    {
        init();

        va_list body;
        va_start(body, szFmt);
        _Put(szKey, szFmt, body);
        va_end(body);
    }

    //MemJson::~MemJson()
    //{
    //    if (IsRoot() && 0 != __cap__)
    //    { // 仅对对象型根节点进行释放（引用型节点__cap__==0）
    //        free((void*)__mem__);
    //    }
    //    if (__buff__ != nullptr)
    //    {
    //        free((void*)__buff__);
    //    }
    //}

    MemJson::Ref MemJson::ToRef()
    {
        Ref ref(*this);
        return ref;
    }

    MemJson::MemJson(THIS_XTYV this_xtyv)
    {
        memset(this, 0, sizeof(MemJsonBase)); // 引用的__cap__必须设为0
        __temp__ = true;
        __parent__ = (MemJsonBase*)this_xtyv.pThis;
        __mem__ = this_xtyv.uXtyV;
        MemJsonBase::Check((void*)__mem__, &__cnt__);
    }

    MemJson::Ref MemJson::New(const char* pszKey)
    {
        MemJson mj;
        MemJsonBase::ValBase vb = __Put(pszKey, 'M', (void*)mj.Mem(), mj.Len());
        return MemJson::Ref(this, vb.v, vb.n);
    }

    const MemJson* MemJson::Root() const
    {
        const MemJson* p_root = this;
        while (p_root->__parent__)
        {
            p_root = (MemJson*)p_root->__parent__;
        }
        return p_root;
    }

    MemJson MemJson::operator[](const char* szKey)
    {
        THIS_XTYV tx;
        Val x = Get(szKey);
        //if (x.IsValid() && x.T == 'M')
        {
            tx.pThis = this;
            tx.uXtyV = x.v;
        }
        return tx;
    }

    MemJson MemJson::operator[](int iKey)
    {
        THIS_XTYV tx;
        Val x = Get(iKey);
        //if (x.IsValid() && x.T == 'M')
        {
            tx.pThis = this;
            tx.uXtyV = x.v;
        }
        return tx;
    }

    MemJson MemJson::operator()(const char* szKey)
    {
        Val x = Get(szKey);
        if (!x.IsValid() || x.T != 'M')
        {
            uint32_t len = MemJson::MIN_LEN;
            MemJsonBase::ValBase vb = __Put(szKey, 'M', (void*)&len, MemJson::MIN_LEN);
            void* p_mem = vb._p_;
            x.read(p_mem, __cnt__ - 1);
        }
        THIS_XTYV tx;
        tx.pThis = this;
        tx.uXtyV = x.v;
        return tx;
    }

    MemJson::Val MemJson::Get(int iKey) const
    {
        if (__mem__ != 0 && iKey >= 0 && iKey < __cnt__)
        {
            Val x_temp((void*)((uint64_t)__mem__ + MemJson::MIN_LEN));
            for (uint32_t i = 0;;)
            {
                if (i == iKey) return x_temp;
                if (++i >= __cnt__) break;
                x_temp.read((void*)((uint64_t)x_temp._p_ + x_temp._n_), i);
            }
        }

        return Val((MemJsonBase*)this);
    }

    MemJson::Val MemJson::Get(const char* szKey) const
    {
        if (szKey && szKey[0] && __cnt__ != 0)
        {
            Val x_temp((void*)((uint64_t)__mem__ + MemJson::MIN_LEN));
            for (uint32_t i = 0;;)
            {
                if (!x_temp.IsValid())
                    break;
                if (strcmp(x_temp.k, szKey) == 0)
                    return x_temp;
                if (++i >= __cnt__)
                    break;
                x_temp.read((void*)((uint64_t)x_temp._p_ + x_temp._n_), i);
            }
        }

        return Val((MemJsonBase*)this);
    }

#pragma endregion
}
